package cn.wizzer.app.web.modules.controllers.open.file;

import cn.wizzer.app.bus.modules.models.BusinessFileInfo;
import cn.wizzer.app.bus.modules.services.BusinessFileInfoService;
import cn.wizzer.app.web.commons.base.Globals;
import cn.wizzer.app.web.commons.slog.annotation.SLog;
import cn.wizzer.app.web.commons.utils.DateUtil;
import cn.wizzer.app.web.commons.utils.StringUtil;
import cn.wizzer.framework.base.Result;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.random.R;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.*;
import org.nutz.mvc.impl.AdaptorErrorContext;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;

/**
 * Created by Wizzer on 2016/7/5.
 */
@IocBean
@At("/open/file/upload")
public class UploadController {

    private static final Log log = Logs.get();
    @Inject
    private BusinessFileInfoService businessFileInfoService;

    @AdaptBy(type = UploadAdaptor.class, args = {"ioc:fileUpload"})
    @POST
    @At
    @Ok("json")
    @RequiresAuthentication
    public Object file1(@Param("Filedata") TempFile tf, HttpServletRequest req, AdaptorErrorContext err) {
        try {
            if (err != null && err.getAdaptorErr() != null) {
                return NutMap.NEW().addv("code", 1).addv("msg", "文件不合法");
            } else if (tf == null) {
                return Result.error("空文件");
            } else {
                return this.uploadFile1(tf, "file");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("系统错误");
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
            return Result.error("文件格式错误");
        }
    }

    @AdaptBy(type = UploadAdaptor.class, args = {"ioc:fileUpload"})
    @POST
    @At
    @Ok("json")
    @RequiresAuthentication
    public Object file(@Param("Filedata") TempFile tf, HttpServletRequest req, AdaptorErrorContext err) {
        try {
            if (err != null && err.getAdaptorErr() != null) {
                return NutMap.NEW().addv("code", 1).addv("msg", "文件不合法");
            } else if (tf == null) {
                return Result.error("空文件");
            } else {
                return this.uploadFile(tf, "file");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("系统错误");
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
            return Result.error("文件格式错误");
        }
    }
    @AdaptBy(type = UploadAdaptor.class, args = {"ioc:videoUpload"})
    @POST
    @At
    @Ok("json")
    @RequiresAuthentication
    //AdaptorErrorContext必须是最后一个参数
    public Object video1(@Param("Filedata") TempFile tf, HttpServletRequest req, AdaptorErrorContext err) {
        try {
            if (err != null && err.getAdaptorErr() != null) {
                return NutMap.NEW().addv("code", 1).addv("msg", "文件不合法");
            } else if (tf == null) {
                return Result.error("空文件");
            } else {
                return this.uploadFile(tf, "video");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("系统错误");
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
            return Result.error("文件格式错误");
        }
    }

    @AdaptBy(type = UploadAdaptor.class, args = {"ioc:imageUpload"})
    @POST
    @At
    @Ok("json")
    @RequiresAuthentication
    //AdaptorErrorContext必须是最后一个参数
    public Object image1(@Param("Filedata") TempFile tf, HttpServletRequest req, AdaptorErrorContext err) {
        try {
            if (err != null && err.getAdaptorErr() != null) {
                return NutMap.NEW().addv("code", 1).addv("msg", "文件不合法");
            } else if (tf == null) {
                return Result.error("空文件");
            } else {
                return this.uploadFile1(tf, "image");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("系统错误");
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
            return Result.error("图片格式错误");
        }
    }


    /**
     * 上传文件
     *
     * @param tf
     * @param fileType
     * @return
     * @throws Exception
     */
    private Object uploadFile(TempFile tf, String fileType) throws Exception {
        //获取上传路径
        String uploadPath = this.getUploadPathConfig();
        //文件后缀名
        String suffixName = tf.getSubmittedFileName().substring(tf.getSubmittedFileName().lastIndexOf(".")).toLowerCase();
        //二三级目录规则
        String filePath = "/" + fileType + "/" + DateUtil.format(new Date(), "yyyyMMdd") + "/";
        //随机文件名
        String uu32 = R.UU32();
        String fileName = uu32 + suffixName;
        //相对路径
        String path = filePath + fileName;
        //绝对路径
        String url = uploadPath + filePath + fileName;
        //将上传的文件拷贝到新路径中
        tf.write(url);
        NutMap map = NutMap.NEW()
                .addv("file_type", suffixName)//返回后缀名
                .addv("file_name", uu32)//返回生成的随机文件名
                .addv("file_size", tf.getSize())//返回文件大小
                .addv("file_path", path)//返回相对路径（相对配置的上传路径）
                .addv("file_url", url);//返回绝对路径
        return Result.success("上传成功", map);
    }

    /**
     * 上传文件
     *
     * @param tf
     * @param fileType
     * @return
     * @throws Exception
     */
    private Object uploadFile1(TempFile tf, String fileType) throws Exception {
        //获取上传路径
        String uploadPath = this.getUploadPathConfig();
        //文件后缀名
        String suffixName = tf.getSubmittedFileName().substring(tf.getSubmittedFileName().lastIndexOf(".")).toLowerCase();
        //二三级目录规则
        String filePath = "/" + fileType + "/" + DateUtil.format(new Date(), "yyyyMMdd") + "/";
        //随机文件名
        String uu32 = R.UU32();
        String fileName = uu32 + suffixName;
        //相对路径
        String path = filePath + fileName;
        //绝对路径
        String url = uploadPath + filePath + fileName;
        //将上传的文件拷贝到新路径中
        tf.write(url);
        BusinessFileInfo report = new BusinessFileInfo();
        report.setInfoName(fileName);
        //report.setInfoVersion(date);
        //report.setInfoType("report");
        report.setRemark("");
        report.setOperatorName(StringUtil.getPlatformUsername());
        report.setFileType(suffixName);
        report.setDisabled(false);
        report.setFilePath(path);
        report.setFileName(fileName);
        report.setFileBeforeName(tf.getSubmittedFileName());
        report.setFileUrl(url);
        businessFileInfoService.insert(report);
        /*NutMap map = NutMap.NEW()
                .addv("file_type", suffixName)//返回后缀名
                .addv("file_name", uu32)//返回生成的随机文件名
                .addv("file_size", tf.getSize())//返回文件大小
                .addv("file_path", path)//返回相对路径（相对配置的上传路径）
                .addv("file_url", url);//返回绝对路径*/
        return Result.success("上传成功", report);
    }


    /**
     * 获取文件上传路径
     *
     * @return
     * @throws Exception
     */
    protected static String getUploadPathConfig() throws Exception {
        String uploadPath;
        //系统没开启配置,上传到项目路径
        if ("false".equals(Globals.MyConfig.getOrDefault("IsConfigUploadPath", "false"))) {
            uploadPath = UploadController.class.getClassLoader().getResource("").getPath() + "upload";
        } else if (
                ("true".equals(Globals.MyConfig.getOrDefault("IsConfigUploadPath", "false"))) && (Globals.MyConfig.getOrDefault("ConfigUploadPath", null) != null)
        ) {
            uploadPath = Globals.MyConfig.get("ConfigUploadPath").toString();
        } else {
            throw new Exception("文件上传路径配置有误");
        }
        return uploadPath;
    }

    @At("/delFile/?")
    @Ok("json")
    @SLog(tag = "删除附件", msg = "删除")
    public Object delFile(String id) {
        try {
            BusinessFileInfo report = businessFileInfoService.fetch(id);
            if (report != null) {
                String uploadPath = this.getUploadPathConfig();
                File file = new File(uploadPath + report.getFilePath());
                if (file.exists()) {
                    if (file.isFile()) {//boolean isFile():测试此抽象路径名表示的文件是否是一个标准文件。
                        file.delete();
                    }
                }
                businessFileInfoService.delete(report.getId());
            }
            return Result.success("删除成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            e.printStackTrace();
            return Result.error("system.error");
        }
    }

    @At("/getFile/?")
    @Ok("json")
    @SLog(tag = "查询附件")
    public Object getFile(String id) {
        try {
            BusinessFileInfo report = businessFileInfoService.fetch(id);
            return Result.success().addData(report);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            e.printStackTrace();
            return Result.error("system.error");
        }
    }

    //    @Inject
//    private FtpService ftpService;

//
//    @AdaptBy(type = UploadAdaptor.class, args = {"ioc:fileUpload"})
//    @POST
//    @At
//    @Ok("json")
//    @RequiresAuthentication
//    //AdaptorErrorContext必须是最后一个参数
//    public Object file(@Param("Filedata") TempFile tf, HttpServletRequest req, AdaptorErrorContext err) {
//        try {
//            if (err != null && err.getAdaptorErr() != null) {
//                return NutMap.NEW().addv("code", 1).addv("msg", "文件不合法");
//            } else if (tf == null) {
//                return Result.error("空文件");
//            } else {
//                String suffixName = tf.getSubmittedFileName().substring(tf.getSubmittedFileName().lastIndexOf(".")).toLowerCase();
//                String filePath = Globals.AppUploadBase + "/file/" + DateUtil.format(new Date(), "yyyyMMdd") + "/";
//                String fileName = R.UU32() + suffixName;
//                String url = filePath + fileName;
//                if (ftpService.upload(filePath, fileName, tf.getInputStream())) {
//                    return Result.success("上传成功", NutMap.NEW().addv("file_type", suffixName).addv("file_name", tf.getSubmittedFileName()).addv("file_size", tf.getSize()).addv("file_url", url));
//                } else {
//                    return Result.error("上传失败，请检查ftp用户是否有创建目录权限");
//                }
//            }
//        } catch (Exception e) {
//            log.error(e.getMessage(), e);
//            return Result.error("系统错误");
//        } catch (Throwable e) {
//            log.error(e.getMessage(), e);
//            return Result.error("文件格式错误");
//        }
//    }
//
//    @AdaptBy(type = UploadAdaptor.class, args = {"ioc:videoUpload"})
//    @POST
//    @At
//    @Ok("json")
//    @RequiresAuthentication
//    //AdaptorErrorContext必须是最后一个参数
//    public Object video(@Param("Filedata") TempFile tf, HttpServletRequest req, AdaptorErrorContext err) {
//        try {
//            if (err != null && err.getAdaptorErr() != null) {
//                return NutMap.NEW().addv("code", 1).addv("msg", "文件不合法");
//            } else if (tf == null) {
//                return Result.error("空文件");
//            } else {
//                String suffixName = tf.getSubmittedFileName().substring(tf.getSubmittedFileName().lastIndexOf(".")).toLowerCase();
//                String filePath = Globals.AppUploadBase + "/video/" + DateUtil.format(new Date(), "yyyyMMdd") + "/";
//                String fileName = R.UU32() + suffixName;
//                String url = filePath + fileName;
//                if (ftpService.upload(filePath, fileName, tf.getInputStream())) {
//                    return Result.success("上传成功", NutMap.NEW().addv("file_type", suffixName).addv("file_name", tf.getSubmittedFileName()).addv("file_size", tf.getSize()).addv("file_url", url));
//                } else {
//                    return Result.error("上传失败，请检查ftp用户是否有创建目录权限");
//                }
//            }
//        } catch (Exception e) {
//            log.error(e.getMessage(), e);
//            return Result.error("系统错误");
//        } catch (Throwable e) {
//            log.error(e.getMessage(), e);
//            return Result.error("文件格式错误");
//        }
//    }
//
//    @AdaptBy(type = UploadAdaptor.class, args = {"ioc:imageUpload"})
//    @POST
//    @At
//    @Ok("json")
//    @RequiresAuthentication
//    //AdaptorErrorContext必须是最后一个参数
//    public Object image(@Param("Filedata") TempFile tf, HttpServletRequest req, AdaptorErrorContext err) {
//        try {
//            if (err != null && err.getAdaptorErr() != null) {
//                return NutMap.NEW().addv("code", 1).addv("msg", "文件不合法");
//            } else if (tf == null) {
//                return Result.error("空文件");
//            } else {
//                String suffixName = tf.getSubmittedFileName().substring(tf.getSubmittedFileName().lastIndexOf(".")).toLowerCase();
//                String filePath = Globals.AppUploadBase + "/image/" + DateUtil.format(new Date(), "yyyyMMdd") + "/";
//                String fileName = R.UU32() + suffixName;
//                String url = filePath + fileName;
//                if (ftpService.upload(filePath, fileName, tf.getInputStream())) {
//                    return Result.success("上传成功", url);
//                } else {
//                    return Result.error("上传失败，请检查ftp用户是否有创建目录权限");
//                }
//            }
//        } catch (Exception e) {
//            log.error(e.getMessage(), e);
//            return Result.error("系统错误");
//        } catch (Throwable e) {
//            log.error(e.getMessage(), e);
//            return Result.error("图片格式错误");
//        }
//    }
}
